<?php
require_once(dirname(__FILE__) ."/DataObject.php");

define("PRIVATE_MESSAGE_FOLDER_INBOX", -1);
define("PRIVATE_MESSAGE_FOLDER_SENT", -2);
define("PRIVATE_MESSAGE_FOLDER_ARCHIVED", -3);
define("PRIVATE_MESSAGE_FOLDER_DELETED", -4);


/*
// Example:


//Creating PrivateMessage Object
$pm = new PrivateMessage();
$pm->setDBLink($dbLink);

$privateMessage->set("fromUserID"  => $user->getID(),
                  "fromGroupID" => $user->getIdentityGroupID(),
                  "subject"     => $_POST['subject'],
                  "body"        => $_POST['body']);

// Send messages to INBOX
if ($privateMessage->send())
{
    echo "Message delivered successfully.";
}
else
{
    echo $privateMessage->getErrorMessage();
}
*/


class PrivateMessage extends DataObject
{
    public $_dbTable = 'privatemessages';
    public $_dbIndex = 'messageID';
    public $_dbUserTable     = "users";
    public $_dbUsernameField = "nickname";
    public $_dbUserIDField   = "userID";
    public $fromUsername;
    public $_arFields = array('owner_userID',
                              'from_userID',
                              'to',
                              'subject',
                              'body',
                              'opened',
                              'folderID',
                              'date_created');

    public function get($opt)
    {
        if (parent::get($opt))
        {
            $sql = "SELECT ". $this->_dbUsernameField ." FROM ". $this->_dbUserTable ." WHERE ". $this->_dbUserIDField ."='". $this->from_userID ."'";
            $this->_mysqlQuery($sql, $result);
            list($this->fromUsername) = mysql_fetch_row($result);
            return 1;
        }
        return 0;
    }

    public function setSubject($subject)
    {
        $this->subject = strip_tags($subject);
    }

    public function setBody($body, $filter=true)
    {
        $this->body = $filter? htmlspecialchars($body) : $body;
    }

    public function getSubject($filter=true)
    {
        return $this->subject;
    }

    public function getBody($filter=true)
    {
        return $this->body;
    }


    public function send($rcpts, $fromUserID=null, $sendCopyToSentMessages=false)
    {
        $this->from_userID = $fromUserID? $fromUserID : $this->from_userID;

        // from_userID must be a valid userID
        if (!(int)$this->from_userID) return $this->_error("Please, provide a valid FROM user ID.");

        // $rcpts must be the (int) userID or a PrivateMessageRecipients object type
        if (!is_a($rcpts, "PrivateMessageRecipients")) return $this->_error("Please, provide a valid PrivateMessageRecipients recipient.");
        if ($rcpts->validate())
        {
            $this->_debugLog(3, get_class($this) ."->send(): starting delivery...");
            $validRecipients = $rcpts->getValids();
            $validRecipientsList = implode(";", array_values($validRecipients));

            // Setting PM vars
            $this->from_userID = $fromUserID;
            $this->to = $validRecipientsList;
            $this->date_created = date("Y-m-d H:i:s");
            $this->folderID = $this->folderID? $this->folderID : PRIVATE_MESSAGE_FOLDER_INBOX;
            $this->opened = "N";

            // 1) sending PM to recipients
            foreach($validRecipients AS $toUserID => $toUsername)
            {
                $this->owner_userID = $toUserID;
                $this->setID(null);
                if (!$this->create()) return $this->_error("Error sending private messate from user $fromUserID to user $toUsername.");
            }

            // 2) if no errors, save message as SENT
            if ($sendCopyToSentMessages)
            {
                $this->_debugLog(3, get_class($this) ."->send(): save message as sent...");
                $this->owner_userID = $fromUserID;
                $this->folderID = PRIVATE_MESSAGE_FOLDER_SENT;
                $this->opened="Y";
                $this->setID(null);
                if (!$this->create()) return $this->_error("Error saving message as sent");
            }
        }
        else return 0;

        return 1;
    }


    public function find($condition, $limit=0, $position=0, $order='', &$result=null)
    {
        $condition = $this->_prepareCondition($condition, true);
        $order = $order? (!strstr($order, "ORDER BY")? " ORDER BY " : "" ) . $order : "";
        $sql = "SELECT pm.*, u.". $this->_dbUsernameField ." AS fromUsername
                FROM ". $this->_dbTable ." AS pm
                LEFT JOIN ". $this->_dbUserTable ." AS u ON (u.". $this->_dbUserIDField ."=pm.from_userID)
                ". $condition . $order . ($limit>0? " LIMIT ". ($position? $position .", " : "") . $limit : '' );
        $this->_mysqlQuery($sql, $this->_mysqlQueryResult);
        $result = $this->_mysqlQueryResult;
        return mysql_num_rows($this->_mysqlQueryResult);
    }

    public function count($ouid, $folder=null, $opened="N")
    {
        $folder = $folder? $folder : PRIVATE_MESSAGE_FOLDER_INBOX;
        $condition = $this->_prepareCondition(array("AND"=>array("owner_userID = '". $ouid ."'", "folderID='". $folder ."'", "opened='". $opened ."'")), true);
        $sql = "SELECT COUNT(*) FROM ". $this->_dbTable ." ". $condition;
        $this->_mysqlQuery($sql, $result);
        $count = mysql_result($result, 0);
        mysql_free_result($result);
        return $count;
    }


    public function fetch($freeResultOnLast=true)
    {
        $this->_debugLog(2, get_class($this) ."->fetch()");
        $DataObjectRow = mysql_fetch_assoc($this->_mysqlQueryResult);

        // fetched after last row..
        if (!$DataObjectRow)
        {
            $this->_debugLog(3, "last data row fetched!");
            mysql_free_result($this->_mysqlQueryResult);
            $this->_mysqlQueryResult = null;
            return 0;
        }

        $this->set($DataObjectRow);
        $this->fromUsername = $DataObjectRow['fromUsername'];
        return 1;
    }


    // marks a message when opened by a user
    public function markAsOpened($mid=0, $uid=0)
    {
        $this->_debugLog(2,get_class($this) ."->markAsOpened($mid, $uid)");

        $messageID = $mid? $mid : $this->getID();
        $owner_userID = $uid? $uid : $this->owner_userID;

        $sql = "UPDATE ".$GLOBALS["CONF"]["db"]["prefix"] . $this->_dbTable ." SET opened='Y' WHERE owner_userID ='". $owner_userID ."' AND messageID = '". $messageID ."'";
        return $this->_mysqlQuery($sql);
    }


    public function moveToFolder($fid, $mid=0, $uid=0)
    {
        $this->_debugLog(2,get_class($this) ."->moveToFolder($fid, $mid, $uid)");

        $this->folderID = $fid;
        $messageID = $mid? $mid : $this->getID();
        $owner_userID = $uid? $uid : $this->owner_userID;

        $sql = "UPDATE ".$GLOBALS["CONF"]["db"]["prefix"] . $this->_dbTable ." SET folderID='". $fid ."' WHERE owner_userID ='". $owner_userID ."' AND messageID = '". $messageID ."'";
        return $this->_mysqlQuery($sql);
    }
}

?>
